'use client';
import React, { useState, useRef, useEffect } from 'react';
import { User, FileText, Calendar, MoreVertical, Trash2 } from 'lucide-react';
import { KnowledgeBase } from './types';

interface KnowledgeCardProps {
  item: KnowledgeBase;
  onCardClick: (item: KnowledgeBase) => void;
  onDelete: (id: string) => void;
}

// 平台配置
const platformConfig = {
  taobao: {
    name: '淘宝',
    color: 'bg-orange-50',
    textColor: 'text-orange-600',
    bgGradient: 'from-orange-50 to-orange-100',
    logo: '🛒',
    brandColor: '#f74200',
  },
  tmall: {
    name: '天猫',
    color: 'bg-red-50',
    textColor: 'text-red-600',
    bgGradient: 'from-red-50 to-red-100',
    logo: '🐱',
    brandColor: '#ed110a',
  },
  pdd: {
    name: '拼多多',
    color: 'bg-red-50',
    textColor: 'text-red-600',
    bgGradient: 'from-red-50 to-red-100',
    logo: '🍊',
    brandColor: '#f60000',
  },
  jd: {
    name: '京东',
    color: 'bg-red-50',
    textColor: 'text-red-600',
    bgGradient: 'from-red-50 to-red-100',
    logo: '🐕',
    brandColor: '#f71501',
  },
  douyin: {
    name: '抖音',
    color: 'bg-green-50',
    textColor: 'text-green-700',
    bgGradient: 'from-green-50 to-green-100',
    logo: '🎵',
    brandColor: '#300a21',
  },
  xiaohongshu: {
    name: '小红书',
    color: 'bg-red-50',
    textColor: 'text-red-600',
    bgGradient: 'from-red-50 to-red-100',
    logo: '📖',
    brandColor: '#df0213',
  },
};

const KnowledgeCard: React.FC<KnowledgeCardProps> = ({
  item,
  onCardClick,
  onDelete,
}) => {
  const [showDropdown, setShowDropdown] = useState(false);
  const dropdownRef = useRef<HTMLDivElement>(null);

  const handleCardClick = (e: React.MouseEvent) => {
    if (dropdownRef.current?.contains(e.target as Node)) return;
    onCardClick(item);
  };

  const handleDelete = async (e: React.MouseEvent) => {
    e.preventDefault();
    e.stopPropagation();

    const confirmed = window.confirm(`您确定要删除"${item.name}"吗？`);
    if (confirmed) {
      onDelete(item.id);
    }
    setShowDropdown(false);
  };

  const handleDropdownToggle = (e: React.MouseEvent) => {
    e.preventDefault();
    e.stopPropagation();
    setShowDropdown(!showDropdown);
  };

  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (
        dropdownRef.current &&
        !dropdownRef.current.contains(event.target as Node)
      ) {
        setShowDropdown(false);
      }
    };

    if (showDropdown) {
      document.addEventListener('mousedown', handleClickOutside);
    } else {
      document.removeEventListener('mousedown', handleClickOutside);
    }

    return () => {
      document.removeEventListener('mousedown', handleClickOutside);
    };
  }, [showDropdown]);

  // 获取平台配置
  const platform = item.platform
    ? platformConfig[item.platform as keyof typeof platformConfig]
    : null;

  // 默认样式
  const defaultStyles = {
    color: 'bg-white',
    textColor: 'text-gray-900',
    bgGradient: 'from-white to-gray-50',
    brandColor: '#6B7280',
  };

  const cardStyles = platform || defaultStyles;

  return (
    <div
      className={`w-84 h-70 p-6 border-2 rounded-xl shadow-sm hover:shadow-lg transition-all duration-300 cursor-pointer relative transform hover:-translate-y-1 ${cardStyles.color}`}
      onClick={handleCardClick}
      style={{
        borderColor: platform ? platform.brandColor : '#E5E7EB',
        background: platform
          ? `linear-gradient(135deg, ${platform.bgGradient
              .replace('from-', '')
              .replace('to-', '')
              .split('-')
              .map((c) => `var(--${c})`)
              .join(', ')})`
          : 'linear-gradient(135deg, #ffffff, #f9fafb)',
      }}
    >
      <div className="h-full flex flex-col justify-between">
        {/* 顶部 - 头像、平台标识和操作 */}
        <div className="flex justify-between items-start">
          <div className="flex items-center gap-3">
            <div className="w-8 h-8 bg-gray-200 rounded-full flex items-center justify-center">
              <User className="w-4 h-4 text-gray-500" />
            </div>
            {/* 平台标识 */}
            {platform && (
              <div className="flex items-center gap-1">
                <span className="text-lg">{platform.logo}</span>
                <span
                  className={`text-xs font-bold px-2 py-1 rounded-full ${platform.textColor} bg-white/70`}
                >
                  {platform.name}
                </span>
              </div>
            )}
          </div>

          <div className="relative dropdown-menu" ref={dropdownRef}>
            <button
              onClick={handleDropdownToggle}
              className="flex items-center p-1 rounded-full hover:bg-white/50 transition-colors z-20 relative"
            >
              <MoreVertical className="w-4 h-4 text-gray-400 hover:text-gray-600" />
            </button>

            {/* 下拉菜单 */}
            {showDropdown && (
              <div className="absolute right-0 top-8 w-32 bg-white border border-gray-200 rounded-lg shadow-lg z-20">
                <button
                  onClick={handleDelete}
                  className="w-full px-3 py-2 text-left text-sm text-red-600 hover:bg-red-50 rounded-lg transition-colors flex items-center gap-2"
                >
                  <Trash2 className="w-3 h-3" />
                  删除
                </button>
              </div>
            )}
          </div>
        </div>

        {/* 中间 - 标题 */}
        <div className="flex-1 my-4 overflow-hidden">
          <h3
            className={`text-2xl font-semibold leading-8 break-all ${cardStyles.textColor}`}
          >
            {item.name}
          </h3>
          {item.description && (
            <p className="mt-2 text-sm font-medium text-gray-600 leading-5 line-clamp-2">
              {item.description}
            </p>
          )}
        </div>

        {/* 底部 - 统计信息 */}
        <div className="space-y-1">
          <div className="flex items-center">
            <FileText className="w-4 h-4 mr-2.5 text-gray-600" />
            <span className="text-xs font-semibold text-gray-700">
              {item.doc_num} Docs
            </span>
          </div>
          <div className="flex items-center">
            <Calendar className="w-4 h-4 mr-2.5 text-gray-600" />
            <span className="text-xs font-semibold text-gray-700">
              {item.update_time}
            </span>
          </div>
        </div>
      </div>
    </div>
  );
};

export default KnowledgeCard;
